#!/bin/sh
#########################################################################################
# (C) Copyright NetEnrich Inc., 2008, All Rights Reserved.                              #
# File Name                     : apply.sh                                              #
# Purpose                       : To upgrade A3000 from 2.6.2 to 3.0                    #
#                               :                                                       #
#                               :                                                       #
#                               :                                                       #
# Version                       : 2.0.                                                  #
# Revision                      :                                                       #
# Original Author               : Ramchander Namani                                     #
# Date                          : Wed Mar  5 14:20:58 IST 2008                          #
# Modification details          :                                                       #
# Reviewed By                   :                                                       #
# tested by                     :                                                       #
#########################################################################################

UPGRADE_PATH=/nems/data/update/scripts
# Untar the zip file.
#patchFileName=appliance.tar.gz
firmwareFileName=MG5000-firmware.tar.gz
STATUS_FILE=$UPGRADE_PATH/statusFile
CURRENT_VPMG_VERSION=""
EMAIL_FILE=$UPGRADE_PATH/emailContent
REMOTE_SUPPORT_STATUS_FILE=$UPGRADE_PATH/remoteSupportStatus

stopNemsapp() {
    # This while loop is added to check whether nemsapp has stopped or not
    # within a maximum of 4 mins
    echo "...Start stopNemsapp..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    count=16
    while [ "$count" -ne "0" ]
    do	
        /usr/local/monit/bin/servicemonit nemsapp stop > /dev/null 2>&1
        /etc/init.d/nemapp status > /dev/null 2>&1
        if [ $? -eq 0 ]
        then
            sleep 15
        else
            echo "...End stopNemsapp..." >> /tmp/patch.log 2>&1
            /bin/date >> /tmp/patch.log 2>&1
            return 0
        fi
        count=`expr $count - 1`
    done
	
    ## If still nemsapp is running, then forcefully kill it.
    catp=`pgrep jsvc`
    if [  "$catp" != "" ]
    then
        kill -9 `pgrep jsvc` > /dev/null 2>&1
        test=`pgrep jsvc`
        if [ "$test" != "" ]
        then
            echo "...End stopNemsapp..." >> /tmp/patch.log 2>&1
            /bin/date >> /tmp/patch.log 2>&1
            return 1
        fi
    fi
    echo "...End stopNemsapp..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    return 0
}

# This method will stop nemsapp and nems database services.
stopServices() {
    echo "...Start stopServices..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    /usr/bin/crontab -r > /dev/null 2>&1
    stopNemsapp
    /usr/local/monit/bin/servicemonit nemsdb stop > /dev/null 2>&1
    /usr/local/monit/bin/servicemonit nemsdb stop > /dev/null 2>&1
    sleep 3
    /etc/init.d/nemsdb stop > /dev/null 2>&1
    /etc/init.d/nemsdb status > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        ## If still nemsapp is running, then forcefully kill it.
        catp=`pgrep postmaster`
        if [  "$catp" != "" ]
        then
            kill -9 `pgrep postmaster` > /dev/null 2>&1
        fi
    fi
    echo "...End stopServices..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
}

updateRPMPackages() {
	echo "updateRPMPackages" > $STATUS_FILE
	echo "...Updating packages..." >> /tmp/patch.log 2>&1
	/bin/date >> /tmp/patch.log 2>&1
	rpm -Uvh /nems/data/update/scripts/packages/*.rpm
	echo "...End of Updating packages..." >> /tmp/patch.log 2>&1
}

getVpmgVersion() {
    CURRENT_VPMG_VERSION=`cat /usr/local/apache/htdocs/admin/build_version.php |grep major.version |cut -d'=' -f2 `.`cat /usr/local/apache/htdocs/admin/build_version.php |grep minor.version |cut -d'=' -f2`
}

sendMail() {
    subject=`/usr/bin/head -n 1 $EMAIL_FILE`
    body=`/usr/bin/tail -n 1 $EMAIL_FILE`
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php SendMailMessage "$subject" "$body"
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php SendVPMGPatchInfo
}

#Restore remote support 
restoreRemoteSupport() {
	if [ -f $REMOTE_SUPPORT_STATUS_FILE ]
	then
		remoteStatus=`/bin/cat $REMOTE_SUPPORT_STATUS_FILE 2>&1`
		/usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php EnableRemoteSupport $remoteStatus
	fi
}

#Clean up. Remove temporary files.
cleanUp() {
    
    restoreRemoteSupport
    echo "updateAdminDB" > $STATUS_FILE
    updateAdminDB
    sendMail
    echo "...Start cleanUp..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    /bin/cat /tmp/patch.log >> /home/admin/logs/patch.log 2>&1
    /bin/chmod 770 /home/admin/logs/patch.log > /dev/null 2>&1
    /bin/chown admin.admin /home/admin/logs/patch.log > /dev/null 2>&1
    /bin/sed '$d' /etc/inittab > $UPGRADE_PATH/tmp/inittab
    /bin/cp -f $UPGRADE_PATH/tmp/inittab /etc/inittab > /dev/null 2>&1
    /bin/chmod 644 /etc/inittab > /dev/null 2>&1

    /bin/rm -rf $UPGRADE_PATH/../xml/* > /dev/null 2>&1
    /bin/rm -rf $UPGRADE_PATH/* > /dev/null 2>&1
    echo "...End cleanUp..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    /bin/rm -f /tmp/patch.log /tmp/install.log > /dev/null 2>&1
    /sbin/telinit q > /dev/null 2>&1
    exit 0
}

deleteDBBackupFile() {
	/usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php deleteBackupFile >> /tmp/patch.log 2>&1
}

disableRemoteSupport() {
    echo "...Start of disable remote support..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
     
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php GetTunnelingInfo > $REMOTE_SUPPORT_STATUS_FILE
     
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php DisableRemoteSupport >> /tmp/patch.log 2>&1
    
    deleteDBBackupFile
    
    echo "...End of disable remote support..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    echo "cleanUp" > $STATUS_FILE
    reboot -f
}

# Add VMPG version to admin UI database which is to be shown in 
updateAdminDB() {
    echo "...Start update Admin DB..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php UpdateUpgradeDB >> /tmp/patch.log 2>&1
    
    echo "...End update Admin DB..." >> /tmp/patch.log 2>&1
}

copyPatch() {
    echo "...Start copyPatch to /firmware..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    /bin/mkdir /nems/firmware > /dev/null 2>&1
    /bin/tar -xzf /firmware/firmware.tar.gz -C /nems/firmware > /dev/null 2>&1
    cd /nems/firmware > /dev/null 2>&1

    # untar MG5000-firmware.tar.gz
    /bin/rm -rf $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    /bin/mkdir -p $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    /bin/tar -xzf $UPGRADE_PATH/$firmwareFileName -C $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1

    cmd=""
    grepCmd="|grep -v "
    cd $UPGRADE_PATH/tmp/firmware
    postgres_size=`/bin/ls -lS|grep postgres.tar.gz|awk '{print $5}'`
    if [ "$postgres_size" == "45" ]
    then
        /bin/cp -f --reply=yes  /nems/firmware/postgres.tar.gz $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    fi

    java_size=`/bin/ls -lS|grep java.tar.gz|awk '{print $5}'`
    if [ "$java_size" == "45" ]
    then
        /bin/cp -f --reply=yes  /nems/firmware/java.tar.gz $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    fi

    apache_size=`/bin/ls -lS|grep apache.tar.gz|awk '{print $5}'`
    if [ "$apache_size" == "45" ]
    then
        /bin/cp -f --reply=yes  /nems/firmware/apache.tar.gz $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    fi
    cp -rf $UPGRADE_PATH/tmp/firmware/* /nems/firmware > /dev/null 2>&1
    cd /nems/firmware > /dev/null 2>&1
    /bin/tar -czf firmware.tar.gz * > /dev/null 2>&1
    /bin/mv -f firmware.tar.gz /firmware > /dev/null 2>&1
    /bin/rm -rf /nems/firmware $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    cd /nems
    echo "...End copyPatch..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    echo "disableRemoteSupport" > $STATUS_FILE
    updateRPMPackages
    getVpmgVersion
    echo "ITMG upgrade is successful" > $EMAIL_FILE
    echo "ITMG upgraded successfully to "$CURRENT_VPMG_VERSION >> $EMAIL_FILE
    disableRemoteSupport
}

restoreDefaultBuild() {
    # First restore default files from /firmware/firmware.tar.gz except data in database.
    echo "...Start restoreDefaultBuild..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    /bin/mkdir /nems/firmware > /dev/null 2>&1
    /bin/tar -xzf /firmware/firmware.tar.gz -C /nems/firmware > /dev/null 2>&1
    cd /nems/firmware > /dev/null 2>&1
        
    /usr/bin/perl install.pl stop.patch.services > /dev/null 2>&1
	/usr/bin/perl install.pl remove.admin.data > /dev/null 2>&1
    /usr/bin/perl install.pl install.menu > /dev/null 2>&1
    /usr/bin/perl install.pl install.merge.xml > /dev/null 2>&1
    /usr/bin/perl install.pl remove.mibfiles > /dev/null 2>&1
    /usr/bin/perl install.pl install.java > /dev/null 2>&1
    /usr/bin/perl install.pl install.apache > /dev/null 2>&1
    /usr/bin/perl install.pl install.webconsole > /dev/null 2>&1
    /usr/bin/perl install.pl install.app > /dev/null 2>&1
    /usr/bin/perl install.pl install.nems > /dev/null 2>&1
    /usr/bin/perl install.pl install.monit > /dev/null 2>&1
    
    TEMP=`grep $UPGRADE_PATH/isApplyRunning.sh /etc/inittab`
    if [ "$TEMP" == "" ]
    then
        echo 'up1:345:once:/bin/sh /nems/data/update/scripts/isApplyRunning.sh' >> /etc/inittab
    fi
    
    /usr/bin/perl install.pl install.sqlite > /dev/null 2>&1
    /usr/bin/perl install.pl install.iptables > /dev/null 2>&1
    /usr/bin/perl install.pl a3000.chkconfig > /dev/null 2>&1
    /usr/bin/perl install.pl a3000.config > /dev/null 2>&1
    /usr/bin/perl install.pl updateModem.Permissions > /dev/null 2>&1
    /usr/bin/perl install.pl generate.config > /dev/null 2>&1
    /usr/bin/perl install.pl update.snmpconf > /dev/null 2>&1
    /usr/bin/perl install.pl install.syslogconf > /dev/null 2>&1
    /usr/bin/perl install.pl restore.applianceConf > /dev/null 2>&1
    /usr/bin/perl install.pl update.ks.version > /dev/null 2>&1
    /usr/bin/perl install.pl install.db.postgres > /dev/null 2>&1
    /usr/bin/perl install.pl default.db.postgres > /dev/null 2>&1
    
    cd /root
    /bin/rm -rf /nems/firmware > /dev/null 2>&1
    getVpmgVersion
    echo "Failed to upgrade ITMG." > $EMAIL_FILE
    echo "ITMG upgrade failed. ITMG reverted back to "$CURRENT_VPMG_VERSION >> $EMAIL_FILE
    echo "...End restoreDefaultBuild..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    disableRemoteSupport
    exit 5
}

callTask() {
    echo "Calling $1." >> /tmp/patch.log 2>&1
    /usr/bin/perl install.pl $1 >> /tmp/patch.log 2>&1
    if [ $? != 0 ]
    then
        echo "restoreDefaultBuild" > $STATUS_FILE
        restoreDefaultBuild
    else
    	echo "Executed $1." >> /tmp/patch.log 2>&1
    fi
}

#NEMS build install
buildInstall() {
    # install script will stop services and install java, apache, tomcat, postgres, 
    # monit and other binary files
    echo "...Start buildInstall..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
	
    cd $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    /bin/sleep 10
	
    callTask stop.crontab

    # Making sure that backup process is done only once.
    if [ ! -e $UPGRADE_PATH/tmp/firmware/backupSuccess ]
    then
        callTask backup.applianceConf
    fi

    touch $UPGRADE_PATH/tmp/firmware/backupSuccess

    callTask stop.patch.services
    callTask update.db.postgres
    callTask install.menu
    callTask update.merge.xml
    callTask update.java
    callTask update.apache
    callTask install.webconsole
    callTask update.app
    callTask install.vmware
    callTask umount.external.storage
    callTask update.nems
    callTask mount.external.storage
    callTask nemsdb.restart
    callTask install.monit
    
    TEMP=`grep $UPGRADE_PATH/isApplyRunning.sh /etc/inittab`
    if [ "$TEMP" == "" ]
    then
        echo 'up1:345:once:/bin/sh /nems/data/update/scripts/isApplyRunning.sh' >> /etc/inittab
    fi
    
    callTask install.sqlite
    callTask install.iptables
    callTask a3000.chkconfig
    callTask a3000.config
    callTask restore.applianceConf
    callTask update.ks.version
    callTask updateModem.Permissions
    callTask generate.config.patch
    callTask update.snmpconf
    callTask restore.CSR
    callTask clear.tmpFiles
    
    echo "...End buildInstall..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
	
    #If everything goes well, then copy the contents of patch to /firmware/firmware.tar.gz
    echo "copyPatch" > $STATUS_FILE
    
    /bin/cat $UPGRADE_PATH/tmp/firmware/install.log >> /home/admin/logs/patch.log 2>&1
    copyPatch
}

updateNemsDatabase() {
    # No need to stop services. The following script doesnt need to
    # stop any service while taking 

    echo "...Start updateNemsDatabase..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    sleep 20
    /usr/bin/crontab -r > /dev/null 2>&1
    /etc/init.d/nemsdb status > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        /usr/local/monit/bin/servicemonit nemsdb start > /dev/null 2>&1
        /etc/init.d/nemsdb start > /dev/null 2>&1
    fi
    stopNemsapp
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php updateDB
    if [ $? != 0 ]
    then
        /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php restoreDB
        cleanUp
        exit 4
    fi
	
    echo "...End updateNemsDatabase..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    echo "buildInstall" > $STATUS_FILE
    buildInstall
}

# Take a complete backup on to VPMG which can be restored again.
# Store the backup file in $UPGRADE_PATH/backup which  will be restored
# (last step in Kernel upgrade process).
takeBackup() {
    # No need to stop services. The following script doesnt need to
    # stop any service while taking backup
    echo "...Start takeBackup..." > /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    #sleep 20
    /usr/bin/crontab -r > /dev/null 2>&1
    /etc/init.d/nemsdb status > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        /usr/local/monit/bin/servicemonit nemsdb start > /dev/null 2>&1
        /etc/init.d/nemsdb start > /dev/null 2>&1
    fi
    #stopNemsapp
    /usr/local/apache/php/bin/php /usr/local/apache/htdocs/admin/ExecFunction.php TakeNEMSDBBackup
    if [ $? != 0 ]
    then
        cleanUp
        exit 3
    fi
	
    # The backup file is /nems/data/backup/appliance/nems-backup
    echo "...End takeBackup..." >> /tmp/patch.log 2>&1
    /bin/date >> /tmp/patch.log 2>&1
    echo "updateNemsDatabase" > $STATUS_FILE
    updateNemsDatabase
}

if [ -f $STATUS_FILE ]
then
    methodToBeCalled=`/bin/cat $STATUS_FILE`
    sleep 120
    $methodToBeCalled
else
    TEMP=`grep $UPGRADE_PATH/isApplyRunning.sh /etc/inittab`
    if [ "$TEMP" == "" ]
    then
        echo 'up1:345:once:/bin/sh /nems/data/update/scripts/isApplyRunning.sh' >> /etc/inittab
    fi

    /bin/rm -rf $UPGRADE_PATH/backup $UPGRADE_PATH/tmp > /dev/null 2>&1
	
    /bin/mkdir -p $UPGRADE_PATH/backup/ > /dev/null 2>&1
    /bin/mkdir -p $UPGRADE_PATH/tmp > /dev/null 2>&1
    #/bin/tar -xf  $UPGRADE_PATH/$patchFileName -C $UPGRADE_PATH/tmp > /dev/null 2>&1
	
    # untar MG5000-firmware.tar.gz
    /bin/mkdir -p $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
    /bin/tar -xzf $UPGRADE_PATH/$firmwareFileName -C $UPGRADE_PATH/tmp/firmware > /dev/null 2>&1
	
    cd $UPGRADE_PATH/tmp/firmware
    /bin/tar -xzf webconsole.tar.gz usr/local/apache/htdocs/admin/ExecFunction.php
    /bin/cp -f usr/local/apache/htdocs/admin/ExecFunction.php /usr/local/apache/htdocs/admin/ExecFunction.php
    #/bin/cp -f home/admin/bin/backupmounts.sh /home/admin/bin/backupmounts.sh
    /bin/rm -rf $UPGRADE_PATH/tmp/firmware/usr > /dev/null 2>&1
	
    cd $UPGRADE_PATH/tmp/firmware
    /bin/tar -xzf nems.tar.gz conf/db/sql > /dev/null 2>&1
    /bin/cp -f conf/db/sql/* /nems/conf/db/sql/ > /dev/null 2>&1
    /bin/chown nems.nems /nems/conf/db/sql -R > /dev/null 2>&1
    /bin/chmod 775 /nems/conf/db/sql -R > /dev/null 2>&1
    /bin/rm -rf conf/ > /dev/null 2>&1
	
    echo "takeBackup" > $STATUS_FILE
    takeBackup
fi

